package com.yunxi.service.dubboService.impl.sto;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import com.yunxi.baseDataToHub.pojo.iam.PmsUserVO;
import com.yunxi.baseDataToHub.service.iam.IamDubboService;
import com.yunxi.core.util.BeanTools;
import com.yunxi.core.util.DESUtil;
import com.yunxi.core.web.ApiResult;
import com.yunxi.model.sto.StoStorageCompany;
import com.yunxi.model.sto.StoStorageStaff;
import com.yunxi.model.sto.StoWorkDay;
import com.yunxi.service.localService.CodeCreateService;
import com.yunxi.service.localService.sto.StoStorageCompanyService;
import com.yunxi.service.localService.sto.StoStorageStaffService;
import com.yunxi.service.localService.sto.StoWorkDayService;
import com.yunxi.sto.pojo.StoStorageStaffUserVO;
import com.yunxi.sto.pojo.StoStorageStaffVO;
import com.yunxi.sto.pojo.StoStorageStaffWorkVO;
import com.yunxi.sto.service.StoStorageStaffDubboService;
import com.yunxi.sys.pojo.RoleUserVO;
import com.yunxi.sys.pojo.UserVO;
import com.yunxi.sys.service.RoleUserDubboService;
import com.yunxi.sys.service.UserDubboService;
import com.yunxi.util.S2SEnums;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 仓储人员 服务实现类
 * </p>
 *
 * @author caoYong
 * @since 2019-06-06
 */
public class StoStorageStaffDubboServiceImpl implements StoStorageStaffDubboService {

    @Autowired
    @Qualifier(value = "stoStorageStaffServiceImpl")
    StoStorageStaffService stoStorageStaffService;

    @Autowired
    @Qualifier(value = "codeCreateServiceImpl")
    CodeCreateService codeCreateService;

    @Autowired
    UserDubboService userDubboServiceImpl;

    @Autowired
    RoleUserDubboService roleUserDubboServiceImpl;

    @Autowired
    @Qualifier(value = "iamDubboServiceImplBiz")
    IamDubboService iamDubboServiceImpl;

    @Autowired
    @Qualifier(value = "stoStorageCompanyServiceImpl")
    StoStorageCompanyService stoStorageCompanyService;

    @Autowired
    @Qualifier(value = "stoWorkDayServiceImpl")
    StoWorkDayService stoWorkDayService;

    @Value("${iam.switch}")
    private Boolean iamSwitch;

    @Override
    public StoStorageStaffVO getById(String id) {
        StoStorageStaffVO stoStorageStaffVO = new StoStorageStaffVO();
        StoStorageStaff stoStorageStaff = stoStorageStaffService.getById(id);
        if(stoStorageStaff != null){
            BeanTools.copyProperties(stoStorageStaffVO,stoStorageStaff);
        }
        return stoStorageStaffVO;
    }

    /**
     * 维护
     */
    @Override
    public void saveOrUpdate(StoStorageStaffVO stoStorageStaffVO) throws Exception{
        boolean isFirst = false;
        String userId = null;
        if(StringUtils.isEmpty(stoStorageStaffVO.getStorageStaffId())){
            isFirst = true;
        }
        else{
            StoStorageStaff byId = stoStorageStaffService.getById(stoStorageStaffVO.getStorageStaffId());
            if(byId != null){
                String storageStaffPhone = byId.getStorageStaffPhone();
                userId = stoStorageStaffService.getUserIdByCode(storageStaffPhone);
            }
        }
        StoStorageStaff stoStorageStaff = new StoStorageStaff();
        BeanTools.copyProperties(stoStorageStaff,stoStorageStaffVO);
        stoStorageStaff = checkStaffName(stoStorageStaff);
        stoStorageStaffService.saveOrUpdate(stoStorageStaff);

        UserVO user = stoStorageStaffVO.getUserVO();
        user.setUserCode(stoStorageStaffVO.getStorageStaffPhone());
        user.setPassword(DESUtil.encrypt(stoStorageStaffVO.getPassWord()));
        user.setRealName(stoStorageStaffVO.getStorageStaffName());
        user.setUserName(stoStorageStaffVO.getStorageStaffName());

        UserVO uservo = userDubboServiceImpl.getByUserCode(stoStorageStaff.getStorageStaffPhone());

        //通过仓储公司诸主键,查询仓储公司编号
        String storageCompanyId = stoStorageStaffVO.getStorageCompanyId();
        StoStorageCompany byId = stoStorageCompanyService.getById(storageCompanyId);
        if(byId != null){
            stoStorageStaffVO.setStorageCompanyNo(byId.getStorageCompanyNo());
        }

        if(uservo==null){
            //需要补充
            //user.setUserNo();
            user = userDubboServiceImpl.save(user);
            RoleUserVO ru = new RoleUserVO();
            ru.setRoleId("cangchusiji");
            ru.setUserId(user.getUserId());
            roleUserDubboServiceImpl.save(ru);
            pms2IAM(stoStorageStaffVO , S2SEnums.OperatorType.insert.getKey());
        }else{
            user.setUserId(uservo.getUserId());
            user = userDubboServiceImpl.saveOrUpdate(user);
            pms2IAM(stoStorageStaffVO , S2SEnums.OperatorType.update.getKey());
        }
        //仓储人员排班,默认全年上班
        setWorkDay(stoStorageStaff);
    }

    /**
     * 维护仓储人员工作日
     * @param stoStorageStaff
     */
    private void setWorkDay(StoStorageStaff stoStorageStaff) {
        String storageStaffId = stoStorageStaff.getStorageStaffId();
        SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy");
        String workYear = simpleDateFormat1.format(new Date());
        StoStorageStaffWorkVO stoStorageStaffWorkVO = new StoStorageStaffWorkVO();
        stoStorageStaffWorkVO.setStaffId(storageStaffId);
        stoStorageStaffWorkVO.setWorkYear(workYear);
        Integer workDayCount = stoStorageStaffService.queryWorkDay(stoStorageStaffWorkVO);
        if(workDayCount != null && !workDayCount.equals(12)){
            stoStorageStaffService.delWorkDay(stoStorageStaffWorkVO);
            int i=0;
            while (i<12){
                StoWorkDay stoWorkDay = new StoWorkDay();
                stoWorkDay.setStaffId(storageStaffId);
                stoWorkDay.setWorkDays("1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31");
                SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("dd");
                Integer format = Integer.valueOf(simpleDateFormat1.format(new Date()));
                Integer format1 = Integer.valueOf(simpleDateFormat2.format(new Date()));
                Calendar instance = Calendar.getInstance();
                instance.set(Calendar.YEAR,format);
                instance.set(Calendar.MONTH,i);
                instance.set(Calendar.DATE,format1);
                Date time = instance.getTime();
                stoWorkDay.setWorkMonth(time);
                stoWorkDayService.saveOrUpdate(stoWorkDay);
                i++;
            }
        }
    }

    private boolean pms2IAM(StoStorageStaffVO staffVO, String op) throws Exception {
        if(iamSwitch){
            PmsUserVO pmsUserVO = new PmsUserVO();
            ArrayList<PmsUserVO> list = new ArrayList<>();
            pmsUserVO.setAccount(staffVO.getStorageStaffPhone());
            pmsUserVO.setPassword(DESUtil.encrypt(staffVO.getPassWord()));
            pmsUserVO.setPartnerCode(staffVO.getStorageCompanyNo());
            pmsUserVO.setUserName(staffVO.getStorageStaffName());
            pmsUserVO.setOperator(op);
            pmsUserVO.setLevel("N");
            list.add(pmsUserVO);
            ApiResult apiResult = iamDubboServiceImpl.sendIamUserVO(list);
            if (apiResult.getCode().equals(-1)) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return true;
            }
        }
        return false;
    }

    /**
     * 校验同公司下人员名称不可重复,手机号不可重复
     * @param stoStorageStaff
     * @return
     * @throws Exception
     */
    private StoStorageStaff checkStaffName(StoStorageStaff stoStorageStaff) throws Exception {
        QueryWrapper<StoStorageStaff> queryWrapper = new QueryWrapper();
        QueryWrapper<StoStorageStaff> queryWrapper1 = new QueryWrapper();
        QueryWrapper<StoStorageStaff> queryWrapper2 = new QueryWrapper<>();
        queryWrapper.eq("STORAGE_STAFF_NAME",stoStorageStaff.getStorageStaffName());
        queryWrapper.eq("STORAGE_COMPANY_ID",stoStorageStaff.getStorageCompanyId());
        queryWrapper1.eq("STORAGE_STAFF_PHONE",stoStorageStaff.getStorageStaffPhone());
        queryWrapper2.eq("RFID",stoStorageStaff.getRfid());
        if(stoStorageStaff.getStorageStaffId() != null){
            queryWrapper.ne("STORAGE_STAFF_ID",stoStorageStaff.getStorageStaffId());
            queryWrapper1.ne("STORAGE_STAFF_ID",stoStorageStaff.getStorageStaffId());
            queryWrapper2.ne("STORAGE_STAFF_ID",stoStorageStaff.getStorageStaffId());
        }
        else {
            String sgs = codeCreateService.createCode("SGS", 4);
            stoStorageStaff.setStorageStaffNo(sgs);
        }
        List<StoStorageStaff> list = stoStorageStaffService.list(queryWrapper);
        if(list != null && list.size() > 0){
            throw new Exception("操作失败,仓储人员名称:"+stoStorageStaff.getStorageStaffName()+"已存在!");
        }
        List<StoStorageStaff> list1 = stoStorageStaffService.list(queryWrapper1);
        if(list1 != null && list1.size() >0){
            throw new Exception("操作失败,仓储人员联系方式:"+stoStorageStaff.getStorageStaffPhone()+"已存在!");
        }
        List<StoStorageStaff> list2 = stoStorageStaffService.list(queryWrapper2);
        if(list2 != null && list2.size() > 0){
            throw new Exception("操作失败,RFID:"+stoStorageStaff.getRfid()+"已绑定其他仓储人员:"+list2.get(0).getStorageStaffName()+"!");
        }
        return stoStorageStaff;
    }

    @Override
    public void removeById(String id) {
        stoStorageStaffService.removeById(id);
    }

    @Override
    public PageInfo<StoStorageStaffVO> findPageByVO(StoStorageStaffVO stoStorageStaffVO, Integer pageNum, Integer pageSize) {
        PageInfo<StoStorageStaffVO> pageInfo = stoStorageStaffService.pageByVo(stoStorageStaffVO, pageNum, pageSize);
        return pageInfo;
    }

    @Override
    public void removeByListVo(List<StoStorageStaffVO> stoStorageStaffVOList) throws IllegalAccessException, InvocationTargetException, InstantiationException {
        stoStorageStaffService.removeByListVo(stoStorageStaffVOList);
    }

    /**
     * 停用/启用
     * @param list
     * @param isOnUse
     * @throws Exception
     */
    @Override
    public void delAndReset(List<String> list, String isOnUse,String userId) throws Exception {
        if(list != null && list.size() > 0){
            for(String id : list){
                StoStorageStaff stoStorageStaff = stoStorageStaffService.getById(id);
                if(stoStorageStaff != null){
                    //如果该人员所属仓储公司已停用,则不可重新启用
                    String storageCompanyId = stoStorageStaff.getStorageCompanyId();
                    StoStorageCompany byId = stoStorageCompanyService.getById(storageCompanyId);
                    if(byId != null){
                        String isOnUse1 = byId.getIsOnUse();
                        if(isOnUse1 != null && isOnUse1.equals("0") && isOnUse.equals("1")){
                            throw new Exception("操作失败,仓储人员:"+stoStorageStaff.getStorageStaffName()+"所属仓储公司已停用,无法启用!");
                        }
                    }
                    stoStorageStaff.setIsOnUse(isOnUse);
                    stoStorageStaff.setUpdateBy(userId);
                    stoStorageStaffService.updateById(stoStorageStaff);
                    //更新用户账户启用停用状态
                    stoStorageStaffService.updateUserStatus(stoStorageStaff);
                    StoStorageStaffVO stoStorageStaffVO = new StoStorageStaffVO();
                    BeanUtils.copyProperties(stoStorageStaff,stoStorageStaffVO);
                    pms2IAM(stoStorageStaffVO , S2SEnums.OperatorType.delete.getKey());
                }
                else{
                    throw new Exception("操作失败,无法根据主键id:"+id+"找到对应仓储人员!");
                }
            }
        }
        else {
            throw new Exception("操作失败,list为空!");
        }
    }

    /**
     * 仓储人员列表
     * @return
     * @throws Exception
     */
    @Override
    public List<StoStorageStaffVO> staffList() throws Exception {
        return stoStorageStaffService.staffList();
    }

    /**
     * 导出
     * @param stoStorageStaffVO
     * @return
     * @throws Exception
     */
    @Override
    public List<StoStorageStaffVO> export(StoStorageStaffVO stoStorageStaffVO) throws Exception {
        return stoStorageStaffService.export(stoStorageStaffVO);
    }

    @Override
    public List<StoStorageStaffUserVO> getStaffList(String positionCode,String partnerCode) {
        StoStorageStaffUserVO stoStorageStaffUserVO = new StoStorageStaffUserVO();
        stoStorageStaffUserVO.setPositionCode(positionCode);
        stoStorageStaffUserVO.setPartnerCode(partnerCode);
        return stoStorageStaffService.getStaffList(stoStorageStaffUserVO);
    }
}
